package com.dj.uphome.web.service;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dj.common.web.exception.InvalidRequestException;
import com.dj.common.web.exception.ServiceHandleException;
import com.dj.common.web.rest.RestClient;
import com.dj.core.MD5;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@Component
@PropertySources(value = {@PropertySource("classpath:web-service.properties")})
public class RestService {
	@Value("${service_app_key}")
	public String appKey;
	@Value("${service_app_secret}")
	public String appSecret;
	@Value("${service_url}")
	public String serviceUrl;
	
	/***
	 * 调用商城Post接口
	 */
	public JSON callPostRequest(String url, Map<String, Object> params) throws InvalidRequestException{
		if(null==params)
			params = new HashMap<String, Object>();
		JSONObject req_head = new JSONObject();
		long timestamp = System.currentTimeMillis();
		req_head.put("app_key", appKey);
		req_head.put("timestamp", timestamp + "");
		JSONObject req_data = new JSONObject();
		for(Map.Entry<String, Object> entry:params.entrySet()){
			req_data.put(entry.getKey(), entry.getValue());
		}
		req_head.put("sign", MD5.md5(timestamp+req_data.toJSONString() + appSecret));
		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<>();
		requestEntity.add("req_head",req_head.toJSONString());
		requestEntity.add("req_data",req_data.toJSONString());
		String result = null;
		try{
			result = RestClient.getClient().postForObject(serviceUrl+url, requestEntity,String.class);
		}catch (Exception e) {
			e.printStackTrace();
		}
		if (!StringUtils.isEmpty(result)) {
			JSONObject json = JSONObject.parseObject(result);
			if(null!=json){
				JSONObject res_msg = (JSONObject)json.get("res_msg");
				if(null!=res_msg&&!StringUtils.equals(res_msg.getString("code"), "0")){
					String message = res_msg.getString("message");
					throw new ServiceHandleException(message);
				}
				return (JSON)json.get("res_data");
			}
		}
		return null;
	}
}
